package netcom;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;

import netcom.messages.BConMessage;
import utilities.Constants;
import utilities.SerializableClassUtility;


public class AnnouncmentThread implements Runnable {

	public static boolean run = true;
	public DatagramSocket c;
	
	int bconId = 0;
	
	public void run() {
	
		while(run){
			try {
				Thread.sleep(Constants.ANNOUNCEMENTS_SLEEP);
				bconId++;
				if(bconId == Integer.MAX_VALUE) bconId = 1;
				
				BConMessage m = new BConMessage(bconId, Constants.SERV_ID, true, Constants.SRV_PORT);
				
				byte[] toSend = SerializableClassUtility.getBytesFromClass(m);
			
				c = new DatagramSocket();
				
				c.setBroadcast(true);	
				DatagramPacket sendPacket = new DatagramPacket(toSend, toSend.length, InetAddress.getByName("255.255.255.255"), Integer.valueOf(Constants.BQ_PORT));
			    c.send(sendPacket);
			    c.close();
			} catch (InterruptedException e) { e.printStackTrace();}
			  catch (SocketException e) { e.printStackTrace(); }
			  catch (IOException e) { e.printStackTrace(); }
		}//end run
		run = false;
		System.err.println("Thread BCAST exit");
	}
	
	
	
	

	
}
